<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { sendFriendRequest } from '@/api/relation.ts';
import {ElMessage} from "element-plus";
// 工具函数：从Token解析用户ID（根据实际Token结构调整字段）
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub; // 假设用户ID存放在JWT的sub字段
  } catch (error) {
    ElMessage.error('Token解析失败:', error);
    return '';
  }
};
// 获取当前用户ID
const getCurrentUserId = (): number => {
  const token = localStorage.getItem('token');
  const userId = getUserIdFromToken(token);
  return userId ? Number(userId) : 6
};

const router = useRouter();
const toUserId = ref<number | null>(null); // 目标用户ID（从路由参数获取）
const currentUserId = getCurrentUserId();
// 表单数据
const greeting = ref(''); // 打招呼内容
const remark = ref('');       // 备注
const tags = ref('');              // 标签
const description = ref('');       // 描述
const privilege = ref('all');      // 朋友权限

onMounted(() => {
  // 从路由参数提取目标用户ID
  const toUserIdStr = router.currentRoute.value.query.toUserId as string;
  if (toUserIdStr) {
    toUserId.value = Number(toUserIdStr);
    console.log("目标用户ID：", toUserId.value); // 调试用
  } else {
    ElMessage.error('参数错误，无法添加好友！');
    router.back(); // 跳回上一页
  }
});

// 发送申请
const sendRequest = async () => {
  if (!currentUserId || !toUserId.value) {
    ElMessage.warning('发送失败');
    return;
  }

  try {
    await sendFriendRequest({
      fromUserId: currentUserId,
      toUserId: toUserId.value,
      requestMsg: greeting.value, // 关键：传递打招呼内容
    });
    ElMessage.success('申请已发送！');
    router.back();
  } catch (error: any) {
    ElMessage.error(`发送失败：${error.response?.data?.msg || '网络异常'}`);
  }
};

</script>

<template>
  <div class="add-friend-request-page">
    <!-- 顶部导航 -->
    <header class="request-header">
      <div class="back-btn" @click="router.back()">
        <svg class="icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
        </svg>
      </div>
      <h1 class="header-title">申请添加朋友</h1>
      <div class="placeholder"></div>
    </header>

    <!-- 表单区域 -->
    <div class="form-section">
      <!-- 打招呼内容 -->
      <div class="form-item">
        <label class="form-label">打招呼内容</label>
        <textarea
            class="form-textarea"
            v-model="greeting"
            placeholder="请输入打招呼内容"
        ></textarea>
        <div class="add-img" @click="">添加图片</div>
        <!-- 扩展：图片上传功能 -->
      </div>

      <!-- 备注 -->
      <div class="form-item">
        <label class="form-label">备注</label>
        <input
            class="form-input"
            v-model="remark"
            placeholder="请输入备注"
        />
      </div>

      <!-- 标签 -->
      <div class="form-item">
        <label class="form-label">标签</label>
        <div class="tag-select" @click="">
          <span>{{ tags || '添加标签' }}</span>
          <svg class="arrow-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </div>
        <!-- 扩展：标签选择页 -->
      </div>

      <!-- 描述 -->
      <div class="form-item">
        <label class="form-label">描述</label>
        <div class="desc-select" @click="">
          <span>{{ description || '添加描述' }}</span>
          <svg class="arrow-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
          </svg>
        </div>
        <!-- 扩展：描述编辑页 -->
      </div>

      <!-- 朋友权限 -->
      <div class="form-item">
        <label class="form-label">朋友权限</label>
        <div class="privilege-group">
          <label class="privilege-item">
            <input type="radio" name="privilege" value="all" v-model="privilege" />
            <span>聊天、朋友圈、微信运动等</span>
          </label>
          <label class="privilege-item">
            <input type="radio" name="privilege" value="chatOnly" v-model="privilege" />
            <span>仅聊天</span>
          </label>
        </div>
      </div>
    </div>

    <!-- 发送按钮 -->
    <div class="action-section">
      <button class="send-btn" @click="sendRequest">发送</button>
    </div>
  </div>
</template>

<style scoped>
.add-friend-request-page {
  background-color: #fff;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

/* 顶部导航 */
.request-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 44px;
  padding: 0 16px;
  border-bottom: 1px solid #eee;
  background-color: #f7f7f7;
}
.back-btn {
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.icon { width: 22px; height: 22px; color: #333; }
.header-title { font-size: 17px; font-weight: 600; margin: 0; }
.placeholder { width: 44px; }

/* 表单区域 */
.form-section { padding: 16px; }
.form-item { margin-bottom: 16px; }
.form-label { display: block; font-size: 14px; color: #333; margin-bottom: 8px; }
.form-textarea {
  width: 100%; height: 80px; padding: 8px;
  border: 1px solid #ddd; border-radius: 8px; resize: none;
  font-size: 14px;
}
.add-img {
  margin-top: 8px; font-size: 12px; color: #07c160;
  cursor: pointer;
}
.form-input {
  width: 100%; padding: 8px;
  border: 1px solid #ddd; border-radius: 8px;
  font-size: 14px;
}
.tag-select, .desc-select {
  display: flex; align-items: center; justify-content: space-between;
  padding: 8px; border: 1px solid #ddd; border-radius: 8px;
  cursor: pointer;
}
.arrow-icon { width: 20px; height: 20px; color: #999; }

.privilege-group { display: flex; flex-direction: column; }
.privilege-item {
  display: flex; align-items: center;
  margin-bottom: 8px;
}
.privilege-item input { margin-right: 8px; }

/* 操作区域 */
.action-section {
  padding: 16px;
  text-align: center;
}
.send-btn {
  width: 100%; max-width: 320px; height: 48px;
  background-color: #07c160; border: none; border-radius: 24px;
  font-size: 16px; color: #fff; cursor: pointer;
}
.send-btn:hover { background-color: #06b054; }
</style>